<template>
  <div class="app-container">
    <div class="filter-container">
      <span v-for="(column, index) in tmpt.columnConditionList" :key="index">
        <el-input
          v-model="listQuery[column.columnName]"
          size="small"
          :placeholder="column.columnName"
          style="width: 200px; margin-left: 5px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
      </span>
      <el-button v-waves class="filter-item" size="small" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-waves class="filter-item" size="small" type="primary" icon="el-icon-search" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        v-for="(column, i) in columnShowList"
        :key="i"
        width="150px"
        align="center"
        :label="column.columnShowName"
        :prop="column.columnName"
        :sortable="column.sortable"
        :sort-orders="['ascending', 'descending']"
      >
        <template slot-scope="{row}">
          <span v-if="column.columnName === 'id'">{{ row[column.columnName] }}</span>
          <span v-else>
            <el-input v-if="row.edit" v-model="row[column.columnName]" class="edit-input" size="mini" />
            <span v-else>{{ row[column.columnName] }}</span>
          </span>
        </template>
      </el-table-column>

      <!--操作Button-->
      <el-table-column fixed="right" label="操作" align="center" min-width="200">
        <template slot-scope="{row}">
          <el-button v-show="row.edit" type="success" size="mini" style="margin-left: 0px;" @click="cancelEdit(row)">取消</el-button>
          <el-button v-if="row.edit" type="success" size="mini" style="margin-left: 0px;" @click="confirmEdit(row)">保存</el-button>
          <el-button v-else type="primary" size="mini" style="margin-left: 0px;" @click="row.edit=!row.edit">编辑</el-button>
          <el-button size="mini" type="danger" style="margin-left: 0px;" onclick="handleDelete(row)">  删除  </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item v-for="(column, i) in tmpt.columnCanAddList" :key="i" :label="column.columnShowName" :prop="column.columnName">
          <el-input v-model="temp[column.columnName]" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getTemplateMapApi, fetchList, updateApi, deleteApi, createApi } from './tmpt-preview-api'
import waves from '@/directive/waves' // waves directive
import { deleteEmptyProperty } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'TmptPreview',
  components: { Pagination },
  directives: { waves },

  props: {
    keyRandomProp: String,
    previewVisible: Boolean
  },

  data() {
    return {
      keyRandom: '',
      tmpt: { // 存储模板数据对象
        mapAll: [],
        columnList: [],
        columnCanAddList: [],
        columnConditionList: []
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        sort: '-id',
        deleteflag: 0
      },
      temp: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      downloadLoading: false,
      dialog4ColumnListVisible: false
    }
  },

  computed: {
    // 过滤只显示可显示的数据
    columnShowList() {
      return this.tmpt.columnList.filter(c => c.isHidden === 0)
    }
  },

  watch: {
    previewVisible(nval) {
      if (nval) {
        this.initLayout()
        this.getList()
      }
    },
    keyRandomProp() {
      this.keyRandom = this.keyRandomProp
      this.initLayout()
      this.getList()
    }/*,
    $route: function(val) {
      this.keyRandom = val.query.keyRandom
      console.log(this.keyRandom)
      // const id = val.params.id*1 ;
      // this.msg = this.msgs.find(msg => id===msg.id);
    }*/
  },

  created() {
    this.keyRandom = this.$route.query.keyRandom
    if (this.keyRandom === undefined) {
      this.keyRandom = this.keyRandomProp
    }

    this.initLayout()
    this.getList()
  },

  methods: {
    initLayout() {
      if (this.keyRandom === undefined) { return }
      getTemplateMapApi({ keyRandom: this.keyRandom }).then(result => {
        this.tmpt.mapAll = result.obj
        this.tmpt.columnCanAddList = result.obj.columnCanAddList
        this.tmpt.columnConditionList = result.obj.conditionColumnMapList
        const columnList = result.obj.columnList

        // 默认按ID排序
        this.tmpt.columnList = columnList.map(c => {
          if (c.columnName === 'id') {
            this.$set(c, 'sortable', 'custom')
          } else {
            this.$set(c, 'sortable', false)
          }
          return c
        })
        console.log(this.tmpt.columnList)
      })
    },

    getList() {
      if (this.keyRandom === undefined) { return }
      this.listLoading = true
      deleteEmptyProperty(this.listQuery)
      this.listQuery._keyRandom = this.keyRandom
      fetchList(this.listQuery).then(result => {
        if (result.success) {
          const items = result.map.rows
          this.total = result.map.total

          // 备份数据，编辑还原用
          this.list = items.map(v => {
            this.$set(v, 'edit', false)
            v.original = Object.assign({}, v)
            return v
          })

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 0.1 * 1000)
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      console.log(data)
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {}
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      /* this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })*/
    },
    createData() {
      const param = Object.assign({}, this.temp)
      param._keyRandom = this.keyRandom
      createApi(param).then((result) => {
        if (result.success) {
          this.handleFilter()
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '添加数据成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },

    handleDelete(row) {
      this.$confirm('删除后，不可恢复；确认删除吗？')
        .then(() => {
          const param = {}
          param._id = row.id
          param._keyRandom = this.keyRandom
          deleteApi(param).then((result) => {
            if (result.success) {
              this.getList()
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        })
        .catch(_ => {})
    },

    cancelEdit(row) {
      // 还原原始值
      Object.keys(row).forEach(key => {
        console.log(key)
        if (key !== 'original' && key !== 'edit') {
          row[key] = row.original[key]
        }
      })
      row.edit = false
      // row.original.edit = false
      this.$message({
        message: '数据恢复到原始值',
        type: 'warning'
      })
    },
    confirmEdit(row) {
      const param = Object.assign({}, row)
      param.original = {}
      param._keyRandom = this.keyRandom
      updateApi(param).then((result) => {
        if (result.success) {
          row.edit = false
          // 原始值：更新成最新输入仠
          Object.keys(row).forEach(key => {
            console.log(key)
            if (key !== 'original' && key !== 'edit') {
              row.original[key] = row[key]
            }
          })
          this.$notify({
            title: '成功',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        }
      })
    }

  }
}
</script>
<style>

</style>
